package de.mediaScan.filesystem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import de.mediaScan.exceptions.NoFolderFoundException;

public class FolderScanner implements IFolderScanner {
	private final List<String> knownMediaFiles;

	public FolderScanner(final List<String> knownMediaFiles) {
		this.knownMediaFiles = knownMediaFiles;
	}

	@Override
	public List<File> scanFolder(final String pathToFolder) throws NoFolderFoundException {
		final List<File> result = new ArrayList<File>();
		final File folder = new File(pathToFolder);

		if (!folder.exists() || !folder.isDirectory()) {
			throw new NoFolderFoundException("No folder found at path: " + pathToFolder);
		}

		final Stack<File> foldersToScan = new Stack<File>();
		foldersToScan.push(folder);

		while (!foldersToScan.empty()) {
			for (final File currentFile : foldersToScan.pop().listFiles()) {
				if (currentFile.isDirectory()) {
					foldersToScan.push(currentFile);
				} else {
					if (this.knownMediaFiles.contains(this.getFileEnding(currentFile))) {
						result.add(currentFile);
					}
				}
			}
		}

		return result;
	}

	/**
	 * This method extracts the ending of a file.
	 * @param file File which ending should be extracted
	 * @return File ending if available the complete filename otherwise
	 */
	private String getFileEnding(final File file) {
		final String fileName = file.getName();

		if (fileName.contains(".")) {
			return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		} else {
			return fileName;
		}
	}
}
